/**
 * Created by Limit on 2017/8/25.
 */

$(document).ready(initializeApp);

var  M={

}
function initializeApp() {
    initializeAppTable();
    initializeAppModal();
    $("#app-input-select").multiSelect({
        afterSelect: function (values) {
            for(var i=0;i<values.length;i++){
                addItem(values[i]);
            }
        },
        afterDeselect: function (values) {
            for(var i=0;i<values.length;i++){
                removeItem(values[i]);
            }
        }
    });
}

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

function initializeAppTable() {

    var url="/cykspark/app/listAll";
    $.ajax({
        url:url,
        dataType:"json",
        success:function (data) {
            bindAppTableData(data);
        }
    });
}

function initializeAppModal() {
    $("#app-add").click(addApp);
}

function bindAppTableData(data) {
    var $tbody=$("#app-row");
    data.forEach(function (item) {
        $tbody.append(getBindRow(item)) ;
    });
}

function getBindRow(row) {

    var $tr=$("<tr></tr>");
    var tdId=document.createElement("td");
    var tdName=document.createElement("td");
    var tdType=document.createElement("td");
    var tdCreateTime=document.createElement("td");
    var tdUpdateTime=document.createElement("td");
    $(tdId).text(row.appId);
    $(tdName).text(row.appName);
    $(tdType).text(row.appType);
    $(tdCreateTime).text(new Date(row.createTime).Format("yyyy-MM-dd hh:mm:ss"));
    $(tdUpdateTime).text(new Date(row.updateTime).Format("yyyy-MM-dd hh:mm:ss"));
    $tr.append(tdId).append(tdName).append(tdType).append(tdCreateTime).append(tdUpdateTime).append(getOperationItem(row.appId));

    return $tr;
}

function getOperationItem(appId) {
    var $tdOperation=$("<td></td>");

    var $ioBtn=$("<button></button>").text("IO").attr("class","operation").attr("data-toggle","modal").attr("data-target","#ioApp").click(function () {
        initializeAppIO(appId);
        $('#app-io-add').click(function () {
            saveAppIO(appId);
        });
        $("#app-io-cancel").click(function () {
          clearSelected();
        });
    });
    var $statusBtn=$("<button></button>").text("状态").attr("class","operation").attr("data-toggle","modal").attr("data-target","#statusApp").click(function () {
        initializeAppStatus(appId);
    });
    var $analysisBtn=$("<button></button>").text("分析").attr("class","operation").click(function () {
        analysisApp(appId);
    });
    var $deleteBtn=$("<button></button>").text("删除").attr("class","operation").click(function () {
        deleteApp(appId);
    });

    $tdOperation.append($ioBtn).append($statusBtn).append($analysisBtn).append($deleteBtn);

    return $tdOperation;
}

function addApp() {
        /****app parameters****/

    var appName=$("#appName").val();
    var appType=$("#appType").find("option:selected").val();
    var appResource=$("#appResource").val();
    var mainClass=$("#mainClass").val();
    var master=$("#master").val();
    var version=$("#clientSparkVersion").val();

    /****Spark Properties****/

    var sparkMaster=$("#spark-master").val();
    var eventLog=$("#spark-eventLog-enabled").find("option:selected").val();
    var sparkAppName=$("#spark-app-name").val();
    var deployMode=$("#spark-submit-deployMode").val();
    var jars=$("#spark-jars").val();
    var supervise=$("#spark-driver-supervise").find("option:selected").val();

    /****Environment Variables****/

    var loaded=$("#SPARK_ENV_LOADED").val();
    var app=new SparkApp(appName,appType);

    app.putAppParameter("appResource",appResource);
    app.putAppParameter("mainClass",mainClass);
    app.putAppParameter("master",master);
    app.putAppParameter("clientSparkVersion",version);


    app.putSparkProperty("spark.master",sparkMaster);
    app.putSparkProperty("spark.eventLog.enabled",eventLog);
    app.putSparkProperty("spark.app.name",sparkAppName);
    app.putSparkProperty("spark.submit.deployMode",deployMode);
    app.putSparkProperty("spark.jars",[]);

    app.putEnvironmentVariable("SPARK_ENV_LOADED",loaded);
    saveApp(app);
}

function deleteApp(appId) {

    var url="/cykspark/app/deleteApp";
    $.ajax({
       url:url,
        dataType:'json',
        data:{
           appId:appId
        },
        success:function (data) {
           if(data){
               if(M.dialog1){
                   return M.dialog1.show();
               }
               M.dialog1 = jqueryAlert({
                   'icon'    : '/cykspark/plugin/alert/img/right.png',
                   'content' : '删除成功!',
                   'closeTime' : 500
               });
              window.setTimeout("window.location.reload()",500); //刷新当前页面.

           }else {
               if(M.dialog2){
                   return M.dialog2.show();
               }
               M.dialog2 = jqueryAlert({
                   'icon'    : '/cykspark/plugin/alert/img/error.png',
                   'content' : '删除失败!',
                   'closeTime' : 500
               });
           }
        },
        error:function () {
            if(M.dialog3){
                return M.dialog3.show();
            }
            M.dialog3 = jqueryAlert({
                'icon'    : '/cykspark/plugin/alert/img/warning.png',
                'content' : '请求失败!',
                'closeTime' : 500
            });
        }
    });
}

function analysisApp(appId) {
    window.open("/cykspark/data/data_show.html?appId="+appId);
}

function saveApp(app) {

    var url="/cykspark/app/createApp";
    $.ajax({
        url:url,
        dataType:'json',
        data:{
            appName:app.getAppName(),
            appType:app.getAppType(),
            parameters:JSON.stringify(app.getParameters())
        },
        success:function (data) {
            console.log(data);
            if(data){
                // 判断是否已存在，如果已存在则直接显示
                if(M.dialog9){
                    return M.dialog9.show();
                }
                M.dialog9 = jqueryAlert({
                    'icon'    : '/cykspark/plugin/alert/img/right.png',
                    'content' : '添加成功！',
                    'closeTime' : 500
                });
               window.setTimeout("window.location.reload()",500);//刷新当前页面.
            }else {
                if(M.dialog4){
                    return M.dialog4.show();
                }
                M.dialog4 = jqueryAlert({
                    'icon'    : '/cykspark/plugin/alert/img/error.png',
                    'content' : '添加失败!',
                    'closeTime' : 500
                });

            }
        },
        error:function () {
            if(M.dialog5){
                return M.dialog5.show();
            }
            M.dialog5 = jqueryAlert({
                'icon'    : '/cykspark/plugin/alert/img/warning.png',
                'content' : '请求失败!',
                'closeTime' : 500
            });
        }
    });
}

function initializeAppIO(appId) {

   var inputUrl="/cykspark/app/getAppIO";
   $.ajax({
      url:inputUrl,
       dateType:'json',
       data:{
          appId:appId
       },
       success:function (data) {
          initializeAppInput(data);
       }
   });

    var outputUrl="/cykspark/app/getApp";
    $.ajax({
        url:outputUrl,
        dataType:'json',
        data:{
            appId:appId
        },
        success:function(data){
            initializeAppOutput(data.appOutput);
        }
    });
}

function initializeAppInput(data) {
    var $input=$('#app-input-select');
   $input.empty();
    var selected=data.selected;
    var unselected=data.unselected;

    selected.forEach(function (item) {
        addItem(item.fileId);
        $input.append($("<option></option>").val(item.fileId).text(item.fileName).attr("selected",true));
    });
    unselected.forEach(function (item) {
        $input.append($("<option></option>").val(item.fileId).text(item.fileName));
    });

    $input.multiSelect('refresh');
}

function initializeAppOutput(data) {


    if ("" !== data) {
        $("#app-output-select").val(data);
    }
}


function saveAppIO(appId) {

    console.log(getSelected());
    var url="/cykspark/app/updateApp";
    $.ajax({
        url:url,
        dataType:'json',
        data:{
            appId:appId,
            input:JSON.stringify(getSelected()),
            output:$("#app-output-select").val()
        },
        success:function (data) {
            console.log(data);
            if(data){
                if(M.dialog6){
                    return M.dialog6.show();
                }
                M.dialog6 = jqueryAlert({
                    'icon'    : '/cykspark/plugin/alert/img/right.png',
                    'content' : '保存成功!',
                    'closeTime' : 500
                });
              window.setTimeout("window.location.reload()",500);  //刷新当前页面.
            }else {
                if(M.dialog7){
                    return M.dialog7.show();
                }
                M.dialog7 = jqueryAlert({
                    'icon'    : '/cykspark/plugin/alert/img/error.png',
                    'content' : '保存失败!',
                    'closeTime' : 500
                });
                alert("保存失败！");
            }
        },
        error:function () {
            if(M.dialog8){
                return M.dialog8.show();
            }
            M.dialog8 = jqueryAlert({
                'icon'    : '/cykspark/plugin/alert/img/warning.png',
                'content' : '请求失败!',
                'closeTime' : 500
            });
        }
    });


}
